<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        .container {
            max-width: 400px;
            margin: 0 auto;
        }
        .upload-box {
            margin-bottom: 20px;
        }
        .result {
            margin-top: 20px;
        }
        .result img {
            max-width: 100%;
            height: auto;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>文件上传</h1>
    <form id="uploadForm" enctype="multipart/form-data">
        <div class="upload-box">
            <label for="fileInput">选择文件：</label>
            <input type="file" id="fileInput" name="file" accept="image/*" required>
        </div>
        <button type="submit">上传</button>
    </form>
    <div class="result" id="result"></div>
</div>

<script>
    document.getElementById('uploadForm').addEventListener('submit', function (e) {
        e.preventDefault(); // 阻止表单默认提交行为

        const fileInput = document.getElementById('fileInput');
        const file = fileInput.files[0];
        if (!file) {
            alert('请选择一个文件！');
            return;
        }

        const formData = new FormData();
        formData.append('file', file);

        // 显示上传状态
        const resultDiv = document.getElementById('result');
        resultDiv.innerHTML = '<p>正在上传...</p>';

        // 发送请求到服务器
        fetch('/upload', {
            method: 'POST',
            body: formData
        })
            .then(response => response.text()) // 获取响应文本
            .then(result => {
                if (result.startsWith('http')) {
                    // 如果返回值是图片 URL，则显示图片
                    resultDiv.innerHTML = `
                    <p>上传成功！</p>
                    <img src="${result}" alt="上传的图片">
                    <p>图片路径：<a href="${result}" target="_blank">${result}</a></p>
                `;
                } else {
                    // 如果返回值不是图片 URL，则显示错误信息
                    resultDiv.innerHTML = `<p style="color: red;">上传失败：${result}</p>`;
                }
            })
            .catch(error => {
                console.error('上传出错:', error);
                resultDiv.innerHTML = `<p style="color: red;">上传出错：${error.message}</p>`;
            });
    });
</script>
</body>
</html>